﻿using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace TLang.Values
{
    public class UnionType : TType
    {

        public readonly HashSet<Value> Values = new HashSet<Value>();


        public UnionType() : base("U")
        {

        }


        public static Value Union(ICollection<Value> values)
        {
            UnionType u = new UnionType();
            foreach (Value v in values)
            {
                u.Add(v);
            }
            if (u.Size() == 1)
            {
                return u.First();
            }
            else
            {
                return u;
            }
        }


        public static Value Union(params Value[] values)
        {
            UnionType u = new UnionType();
            foreach (Value v in values)
            {
                u.Add(v);
            }
            if (u.Size() == 1)
            {
                return u.First();
            }
            else
            {
                return u;
            }
        }


        public void Add(Value value)
        {
            if (value is UnionType) {
                foreach (var item in ((UnionType)value).Values)
                {
                    Values.Add(item);
                }
            } else {
                Values.Add(value);
            }
        }


        public int Size()
        {
            return Values.Count;
        }


        public Value First()
        {
            return Values.First();
        }


        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(Constants.ParenBegin).Append("U ");

            bool first = true;
            foreach (Value v in Values)
            {
                if (!first)
                {
                    sb.Append(" ");
                }
                sb.Append(v);
                first = false;
            }

            sb.Append(Constants.ParenEnd);

            return sb.ToString();
        }
    }
}
